using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

namespace ServiceControllerApp.Models
{
    public class AppConfig
    {
        public List<string> ServiceNames { get; set; } = new List<string>();
        
        private static readonly string ConfigFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "ServiceControllerApp",
            "config.json"
        );

        public static AppConfig Load()
        {
            try
            {
                if (File.Exists(ConfigFilePath))
                {
                    string jsonContent = File.ReadAllText(ConfigFilePath);
                    var config = JsonSerializer.Deserialize<AppConfig>(jsonContent);
                    return config ?? CreateDefault();
                }
            }
            catch (Exception)
            {
                // 如果加载失败，返回默认配置
            }
            
            return CreateDefault();
        }

        public void Save()
        {
            try
            {
                string? directory = Path.GetDirectoryName(ConfigFilePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var options = new JsonSerializerOptions { WriteIndented = true };
                string jsonContent = JsonSerializer.Serialize(this, options);
                File.WriteAllText(ConfigFilePath, jsonContent);
            }
            catch (Exception)
            {
                // 保存失败时静默处理
            }
        }

        private static AppConfig CreateDefault()
        {
            return new AppConfig
            {
                ServiceNames = new List<string> { "CCDQ_Work", "CCDQ_Nginx", "MySQL80", "OpenObserveService" }
            };
        }
    }
} 